昨天提到,useEffect會在第一次render和每一次更新後被觸發,但我們也可以透過他的第二個參數dependency
來控制他的觸發狀態。
用法是這樣的。
dependency
的情況下,{count}
的更新,也會觸發{calculation}
的更新,因為每一次更新都會觸發useEffect
function App() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);
useEffect(() => {
setCalculation(() => count );
}); // <- add the count variable here
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</>
);
}
dependency
設定為空陣列。useEffect
會根據後面的參數是否改變,來選擇要不要觸發,而空陣列永遠都是空陣列,不會變化。useEffect
之後,就不會再更新了。useEffect
,就在第二個參數後面放上空陣列。function App() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);
useEffect(() => {
setCalculation(() => count );
}, []); // <- add the count variable here
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</>
);
}
dependency
設定為某個數值,在這裡我們設定為[count]
,也就是說,當count
改變,就會觸發 useEffect
。function App() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);
useEffect(() => {
setCalculation(() => count );
}, [count]); // <- add the count variable here
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</>
);
}
嗚嗚,透過三天,我終於把useEffect
搞懂了(吧?)
感謝飛天小女警的努力,一天又平安的度過了,讓我們明天見!